<?php
namespace Admin\Model;
use Think\Model;

class VisitModel extends Model{
	//查询总记录
	public function total(){
		return $this->where($this->map())->count();
	}
	
	//查询所有
	public function all($firstRow){
		return $this->field('ip,url,count,date1,date2')
					->where($this->map())
					->order(array('date2'=>'DESC'))
					->limit($firstRow,C('PAGE_SIZE'))
					->select();
	}
	
	//查询所有（不分页）
	public function all2(){
		return $this->field('ip,url,count,date1,date2')
					->order(array('date2'=>'DESC'))
					->select();
	}
	
	//查询昨天是否有记录
	public function yesterday(){
		$map = array(
			'date1'=>array('LT',strtotime(date('Y-m-d').' 00:00:00'))
		);
		return $this->field('id')
					->where($map)
					->find();
	}
	
	//查询一条
	public function one(){
		$map = array(
			'ip'=>$_SERVER['REMOTE_ADDR'],
			'url'=>I('post.url'),
			'date1'=>array('EGT',strtotime(date('Y-m-d').' 00:00:00')),
			'date2'=>array('ELT',strtotime(date('Y-m-d').' 23:59:59'))
		);
		return $this->field('id')
					->where($map)
					->find();
	}
	
	//添加
	public function insert(){
		$data = array(
			'ip'=>$_SERVER['REMOTE_ADDR'],
			'url'=>I('post.url'),
			'count'=>1,
			'date1'=>NOW_TIME,
			'date2'=>NOW_TIME
		);
		return $this->add($data);
	}
	
	//修改
	public function update($id){
		$data = array(
			'id'=>$id,
			'date2'=>NOW_TIME
		);
		$this->where(array('id'=>$id))->setInc('count');
		return $this->save($data);
	}
	
	//清空表
	public function truncate(){
		return $this->execute('TRUNCATE `__PREFIX__visit`');
	}
	
	//搜索
	private function map(){
		$map = array(
			'_complex'=>array(
				'ip'=>array('like','%'.I('get.keyword').'%'),
				'url'=>array('like','%'.I('get.keyword').'%'),
				'_logic'=>'OR'
			)
		);
		return $map;
	}
}